package psn.zjk.common.jvm;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;

import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @USER white
 * @DATETIME 2021/1/10 9:30
 */
public class FullGC {
    private LinkedList<Object> list = new LinkedList<>();

    public void memoryLeak(){
        while (true){
            for (int i = 0; i < 2; i++) {
                list.add(createLarge(RandomUtils.nextInt(0,100)));
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void createAndDestroy() {
       while (true){
           for (int i = 0; i < 5; i++) {
               list.add(createLarge(RandomUtils.nextInt(0,100)));
           }
           for (int i = 0; i < 5; i++) {
               list.remove();
           }
           try {
               Thread.sleep(100);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
    }


    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.execute(() -> {new FullGC().createAndDestroy();});
        executorService.execute(() -> {new FullGC().memoryLeak();});

        //内存溢出后线程回挂掉，内存被回收
//        new FullGC().memoryLeak();
    }


    public  Object createSmall(){
        return new Object();
    }
    public  Object createLarge(int sizeK){
        return RandomStringUtils.random(sizeK*1024/3);
    }

}
